package JAVA300.第十章IO;

import java.io.*;

/**
 * p180-释放资源代码
 * try..with..resource jdk1.7自动释放资源
 */

public class MyFileUtil02 {
    public static void main(String[] args) {
        //文件到文件
        try {
            InputStream is = new FileInputStream("IOTest01.txt");//内部new了file对象了
            OutputStream os = new FileOutputStream("IOTest01_MyFileUtil.txt");
            CopyFile(is,os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //文件到字节数组
        byte[] out= null;
        try {
            InputStream is1 = new FileInputStream("testpic.png");
            ByteArrayOutputStream boas = new ByteArrayOutputStream();
            CopyFile(is1,boas);
            out = boas.toByteArray();
            System.out.println(out.length);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        //字节数组到文件
        try {
            InputStream is2 = new ByteArrayInputStream(out);
            OutputStream os = new FileOutputStream("testpic_MyFileUtil.png");
            CopyFile(is2,os);


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }


    //from IO_Study05_Method--实现给输出输入流即可完成 不用判断是哪类流
    public static void CopyFile(InputStream is,OutputStream os){

        try{//(is;os) 1.8版本不支持
            int len;
            byte[] flush = new byte[1024];
            while ((len = is.read(flush)) != -1){
                os.write(flush,0,len);
            }
            os.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
